<template>
    <div>
        <el-page-header @back="goBack" :content="$route.name"></el-page-header>
        <el-form
            class="add"
            style="margin: 20px;"
            :label-position="labelPosition"
            label-width="120px"
            :model="addEquipment"
            :rules="addRules"
            ref="addEquipment"
        >
            <el-form-item label="设备号：" prop="number">
                <el-input clearable v-model="addEquipment.number" placeholder="请输入设备号"></el-input>
            </el-form-item>
            <el-form-item label="商户号：" prop="business_id">
                <el-select v-model="addEquipment.business_id" placeholder="请选择所在商户">
                    <el-option v-for="item in businessname" :key="item.id" :label="item.name+'('+item.merchant_num+')'" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="城市：" prop="city">
                <el-select clearable v-model="addEquipment.city">
                    <el-option
                        v-for="(item,index) in cityList"
                        :key="index"
                        :label="item.city"
                        :value="item.cityValue"
                    ></el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item label="门店名称：" prop="shop_id">
                <!-- <el-input clearable v-model="addEquipment.shop_id" placeholder="请输入门店名称"></el-input> -->
                <el-select v-model="addEquipment.shop_id" placeholder="请选择对应的门店">
                    <el-option v-for="item in shopname" :key="item.id" :label="item.city+'('+item.name+')'" :value="item.id" v-show="item.business_id === addEquipment.business_id"></el-option>
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="店员数量：" prop="storeNumber">
                <el-input v-model="addEquipment.storeNumber" placeholder="请输入店员数量"></el-input>
            </el-form-item>-->
            <!-- <el-form-item label="门店地址：" prop="storeAddress">
                <el-input id="suggestId" v-model="addEquipment.storeAddress" placeholder="请输入门店地址"></el-input>
            </el-form-item> -->
            <!-- <el-form-item>
                <div id="l-map" style="width:500px;height:300px;"></div>
                <div
                    id="searchResultPanel"
                    style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"
                ></div>
            </el-form-item> -->
            <!-- <el-form-item label="门店环境：" prop="storeUrl">
                <el-upload
                    ref="storeUrl"
                    v-model="addEquipment.storeUrl"
                    :action="addUploadUrl"
                    :show-file-list="false"
                    list-type="picture-card"
                    :before-upload="addEquipmentUpload"
                    :on-preview="addEquipmentPreview"
                    :http-request="addEquipmentUploadEvent"
                    :on-exceed="addEquipmentExceedLimit"
                    :on-remove="addEquipmentRemove"
                >
                    <img v-if="addEquipment.storeUrl" :src="addEquipment.storeUrl" class="avatar" />
                    <i v-else class="el-icon-plus"></i>
                </el-upload>
            </el-form-item> -->
            <el-form-item label="加盟方式：" prop="type">
                <el-select clearable v-model="addEquipment.type">
                    <el-option
                        v-for="(item,index) in joinWayList"
                        :key="index"
                        :label="item.type"
                        :value="item.joinWayValue"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备状态">
                <el-select v-model="addEquipment.state">
                    <el-option v-for="item in statusList" :key="item.value" :label="item.status" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注信息：" prop="note">
                <el-input type="textarea" v-model="addEquipment.note" placeholder="请输入内容"></el-input>
            </el-form-item>

            <!-- <el-form-item label="运行状态" prop="status">
                <el-select v-model="addEquipment.status">
                    <el-option
                        v-for="(item,index) in statusList"
                        :key="index"
                        :label="item.status"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>-->
            <!-- <el-form-item label="普通洗价格：">
                <el-input v-model="addEquipment.fastPrice" placeholder="请输入普通洗价格"></el-input>
                <span>元</span>
            </el-form-item>
            <el-form-item label="精洗价格：">
                <el-input v-model="addEquipment.exquisitePrice" placeholder="请输入精洗价格"></el-input>
                <span>元</span>
            </el-form-item>
            <el-form-item label="营业起始时间：">
                <el-time-select
                    placeholder="请选择起始时间"
                    v-model="addEquipment.startTime"
                    :picker-options="{start: '06:00',step: '00:15',end: '24:00'}"
                ></el-time-select>
            </el-form-item>
            <el-form-item label="营业结束时间：">
                <el-time-select
                    placeholder="请选择结束时间"
                    v-model="addEquipment.endTime"
                    :picker-options="{start: '06:00',step: '00:15',end: '24:00',minTime: addEquipment.startTime}"
                ></el-time-select>
            </el-form-item>-->
            <el-form-item>
                <el-button
                    style="margin-left:50px;"
                    size="medium"
                    type="primary"
                    @click="confirm()"
                >确认修改</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import "../../../../static/scss/page.scss";
import utils from "../../../util/request";
export default {
    data() {
        return {
            labelPosition: "right",
            latitude: "", //纬度
            longitude: "", //经度
            addUploadUrl: "", //上传服务器路径
            dialogVisible: false, //预览图片对话框
            dialogImageUrl: "", //预览图片的路径
            businessname:{},
            shopname:{},
            addEquipment: {
                id: "",
                number: "", //设备号
                business_id: "",
                shop_id: "",
                type: "", //加盟方式
                note: "",
                state: ""
                // storeId: "", //店铺id
                // equipmentNumber: "", //设备号
                // merchantNumber: "", //商户号
                // city: "", //城市
                // storeName: "", //门店名称
                // storeAddress: "", //门店地址
                // storeUrl: "", //门店环境图
                // joinWay: "" //加盟方式
            },
            addRules: {
                // 表单验证
                number: [
                    { required: true, message: "请输入设备号", trigger: "blur" }
                ],
                city: [
                    {
                        required: true,
                        message: "请选择城市",
                        trigger: "change"
                    }
                ],
                shop_id: [
                    {
                        required: true,
                        message: "请选择门店名称",
                        trigger: "blur"
                    }
                ],
                storeNumber: [
                    {
                        required: true,
                        message: "请输入店员数量",
                        trigger: "blur"
                    }
                ],
                storeAddress: [
                    {
                        required: true,
                        message: "请输入门店地址",
                        trigger: "blur"
                    }
                ],
                storeUrl:[
                    {
                        required: true,
                        message: "请选择图片",
                        trigger: "change"
                    }
                ],
                type: [
                    {
                        required: true,
                        message: "请选择加盟方式",
                        trigger: "change"
                    }
                ]
            },
            cityList: [
                {
                    city: "深圳",
                    cityValue: "深圳"
                },
                {
                    city: "北京",
                    cityValue: "北京"
                },
                {
                    city: "上海",
                    cityValue: "上海"
                },
                {
                    city: "广州",
                    cityValue: "广州"
                }
            ],
            joinWayList: [
                {
                    type: "个人加盟",
                    joinWayValue: 0
                },
                {
                    type: "企业加盟",
                    joinWayValue: 1
                },
                {
                    type: "自营",
                    joinWayValue: 2
                }
            ],
            statusList: [
                {
                    status: "待机",
                    value: 0
                },
                {
                    status: "正在使用",
                    value: 1
                },
                {
                    status: "故障",
                    value: 2
                },
                {
                    status: "洗车",
                    value: 3
                }
            ]
        };
    },
    methods: {
        goBack: function() {
            // 页头的返回
            this.$router.go(-1);
        },
        theLocation(lon, lat) {
            let map = new BMap.Map("l-map");
            let point = new BMap.Point(116.331398, 39.897445);
            map.centerAndZoom(point, 18);
            map.enableScrollWheelZoom(true);
            console.log("123");
            // 用经纬度设置地图中心点
            console.log(lon, lat);
            if (lon != "" && lat != "") {
                map.clearOverlays();
                let new_point = new BMap.Point(lon, lat);
                let marker = new BMap.Marker(new_point); // 创建标注
                map.addOverlay(marker); // 将标注添加到地图中
                map.panTo(new_point);
            }
        },
        addEquipmentPreview(file) {
            // 点击文件列表中已上传的文件时的钩子
            console.log(file);
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        addEquipmentExceedLimit() {
            // 项目图片超过数量限制事件
            this.$message({
                type: "error",
                message: "上传图片数量已达到限制!"
            });
        },
        addEquipmentUpload(file) {
            // 上传图片之前的钩子
            console.log(file);
            return new Promise((resolve, reject) => {
                let _URL = window.URL || window.webkitURL;
                let isLt2M = file.size / 1024 / 1024 > 0.3; // 判定图片大小是否小于0.3MB
                // 这里需要计算出图片的长宽
                let img = new Image();
                img.onload = function() {
                    file.width = img.width; // 获取到width放在了file属性上
                    file.height = img.height; // 获取到height放在了file属性上
                    let valid = img.width > 2000; // 图片宽度大于2000
                    // console.log(11, file)
                    // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
                    if (valid || isLt2M) {
                        compressAccurately(file, {
                            size: 100,
                            width: 690
                        }).then(res => {
                            // console.log(33, res)
                            resolve(res);
                        });
                    } else resolve(file);
                }; // 需要把图片赋值
                img.src = _URL.createObjectURL(file);
            });
        },
        addEquipmentUploadEvent(file) {
            // 图片上传至服务器
            console.log(file);
            // let formData = new FormData();
            // formData.append("file", file.file);
            // console.log(formData);
            // let instance = axios.create({
            //     baseURL: "https://admin.jljinhong.club/",
            //     headers: {
            //         Authorization: "Bearer " + localStorage.jh_token, //token
            //         "Content-Type": "multipart/form-data"
            //     }
            // });
            // instance.post("ImageUpload", formData).then(res => {
            //     console.log(res);
            //     if (res.data.code == 20000) {
            //         this.addEquipment.storeUrl = res.data.data; //表单里的图片路径
            //         console.log(this.addEquipment.storeUrl);
            //     }
            //     if (res.data.code == 20004) {
            //         this.$message({
            //             type: "error",
            //             message: "请重新登录!"
            //         });
            //         this.$router.push({ path: "/" });
            //     }
            //     if (res.data.code == 20008) {
            //         this.$message({
            //             type: "error",
            //             message: "图片过大，请上传小于5M的图片!"
            //         });
            //     }
            // });
        },
        addEquipmentRemove: function(file, fileList) {
            // 上传完成时在文件列表里移除的事件
            console.log(file, fileList);
            // let src = this.addEquipment.storeUrl;
            // let indexOf = src.lastIndexOf("/"); //找到图片路径的最后一个斜杠
            // let fileName = src.substring(indexOf + 1); //最后一个斜杠加一表示找到了图片的名字中的第一位
            // console.log(fileName);
            // request
            //     .request("ImageDELETE?fileName=" + fileName, "delete")
            //     .then(res => {
            //         console.log(res);
            //         if (res.data.code == 20000) {
            //             this.$message({
            //                 type: "success",
            //                 message: "删除成功!"
            //             });
            //             this.addEquipment.storeUrl = ""; //表单里的图片路径为空
            //         }
            //         if (res.data.code == 20001) {
            //             this.$message({
            //                 type: "error",
            //                 message: "删除失败或文件不存在！"
            //             });
            //         }
            //     });
        },
        confirm() {
            // 确认修改
            let that = this;

            this.$refs["addEquipment"].validate(valid => {
                if (valid) {
                    let that = this;
                    // console.log(this.addEquipment)
                    let data = {};
                    for(var i in this.addEquipment) this.addEquipment[i] !== "" ? data[i] = this.addEquipment[i] : "";
                    utils.request("/equipment/update","post",JSON.stringify(data)).then(resp=>{
                        console.log(resp.data)
                        if(resp.data.code === 200 && resp.data.data === 1){
                            this.$message({
                                message: "设备数据已更新",
                                type: "success"
                            })
                            this.$router.push("/equipment")
                        }else{return false}
                    })
                    // let location = that.longitude + "," + that.latitude;
                    // console.log(location);
                    // utils
                    //     .request("store", "put", {
                    //         storeId: that.addEquipment.storeId, //店铺id
                    //         machine: that.addEquipment.equipmentNumber, //设备号
                    //         storeName: that.addEquipment.storeName, //门店名称
                    //         clerkNum: that.addEquipment.storeNumber, //店员数量
                    //         address: that.addEquipment.storeAddress, //门店地址
                    //         location: location, //位置信息
                    //         onePrice: parseFloat(that.addEquipment.fastPrice), //普通洗价格
                    //         twoPrice: parseFloat(
                    //             that.addEquipment.exquisitePrice
                    //         ), //精洗价格
                    //         startTime: that.addEquipment.startTime, //营业开始时间
                    //         endTime: that.addEquipment.endTime //营业结束时间
                    //     })
                    //     .then(res => {
                    //         console.log(res);
                    //         if (res.data.code === 20000) {
                    //             that.$message({
                    //                 type: "success",
                    //                 message: "修改成功!"
                    //             });
                    //             that.$router.go(-1);
                    //         } else if (res.data.code === 20004) {
                    //             that.$message({
                    //                 type: "error",
                    //                 message: "请重新登录！"
                    //             });
                    //             that.$router.push("/");
                    //         } else if (res.data.code === 20005) {
                    //             that.$message({
                    //                 type: "error",
                    //                 message: res.data.msg
                    //             });
                    //         }
                    //     });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        }
    },
    // mounted() {
    //     let that = this;
    //     // 百度地图API功能
    //     function G(id) {
    //         return document.getElementById(id);
    //     }

    //     var map = new BMap.Map("l-map");
    //     var point = new BMap.Point(116.331398, 39.897445);
    //     map.centerAndZoom(point, 12);

    //     // // 初始化地图,设置城市和地图级别。
    //     // var geolocation = new BMap.Geolocation();
    //     // geolocation.getCurrentPosition(
    //     //     function(r) {
    //     //         if (this.getStatus() == BMAP_STATUS_SUCCESS) {
    //     //             var mk = new BMap.Marker(r.point);
    //     //             map.addOverlay(mk);
    //     //             map.panTo(r.point);
    //     //         } else {
    //     //             // alert("failed" + this.getStatus());
    //     //         }
    //     //     },
    //     //     { enableHighAccuracy: true }
    //     // );

    //     var ac = new BMap.Autocomplete({ input: "suggestId", location: map }); //建立一个自动完成的对象

    //     ac.addEventListener("onhighlight", function(e) {
    //         //鼠标放在下拉列表上的事件
    //         var str = "";
    //         var _value = e.fromitem.value;
    //         var value = "";
    //         if (e.fromitem.index > -1) {
    //             value =
    //                 _value.province +
    //                 _value.city +
    //                 _value.district +
    //                 _value.street +
    //                 _value.business;
    //         }
    //         str =
    //             "FromItem<br />index = " +
    //             e.fromitem.index +
    //             "<br />value = " +
    //             value;

    //         value = "";
    //         if (e.toitem.index > -1) {
    //             _value = e.toitem.value;
    //             value =
    //                 _value.province +
    //                 _value.city +
    //                 _value.district +
    //                 _value.street +
    //                 _value.business;
    //         }
    //         str +=
    //             "<br />ToItem<br />index = " +
    //             e.toitem.index +
    //             "<br />value = " +
    //             value;
    //         G("searchResultPanel").innerHTML = str;
    //     });

    //     var myValue;
    //     ac.addEventListener("onconfirm", function(e) {
    //         //鼠标点击下拉列表后的事件
    //         var _value = e.item.value;
    //         myValue =
    //             _value.province +
    //             _value.city +
    //             _value.district +
    //             _value.street +
    //             _value.business;
    //         G("searchResultPanel").innerHTML =
    //             "onconfirm<br />index = " +
    //             e.item.index +
    //             "<br />myValue = " +
    //             myValue;

    //         setPlace();
    //     });

    //     function setPlace() {
    //         map.clearOverlays(); //清除地图上所有覆盖物
    //         function myFun() {
    //             var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
    //             map.centerAndZoom(pp, 18);
    //             map.addOverlay(new BMap.Marker(pp)); //添加标注
    //             that.latitude = pp.lat; //纬度
    //             that.longitude = pp.lng; //经度
    //             console.log(pp.lat, pp.lng); //选中的位置地址经纬度
    //         }
    //         var local = new BMap.LocalSearch(map, {
    //             //智能搜索
    //             onSearchComplete: myFun
    //         });
    //         local.search(myValue);
    //         that.addEquipment.storeAddress = myValue; //门店地址
    //         console.log(myValue); //选中的位置地址内容
    //     }
    // },
    created() {
        // console.log(JSON.parse(this.$route.query.row));
        let row = JSON.parse(this.$route.query.row);
        utils.request("/business/list","post",JSON.stringify({page:1,list_rows:999999999,level:"0"})).then(resp=>{
            this.businessname = resp.data.data.data
        })
        utils.request("/shop/list","post",JSON.stringify({page:1,list_rows:999999999})).then(resp=>{
            this.shopname = resp.data.data.data
        })
        for(var i in this.addEquipment) this.addEquipment[i] = row[i];
        // console.log(this.addEquipment,row)
        if (row !== "[object Object]") {
            // utils
            //     .request("stores", "post", {
            //         storeId: row.storeId,
            //         deleteFlag: 0, //查询存续
            //         pageStart: this.currentPage, //页面
            //         pageRequestSize: this.currentCount //请求数据数量
            //     })
            //     .then(res => {
            //         console.log(res);
            //         if (res.data.code === 20000) {
            //             let data = res.data.dataList;
            //             data.forEach(item => {
            //                 let location = item.location;
            //                 let arr = location.split(",");
            //                 console.log(arr);
            //                 (this.addEquipment.storeId = item.storeId), //店铺id
            //                     (this.addEquipment.equipmentNumber =
            //                         item.machine); //订单号
            //                 this.addEquipment.storeName = item.storeName; //门店名称
            //                 this.addEquipment.storeNumber = item.clerkNum; //店员数量
            //                 this.addEquipment.storeAddress = item.address; //门店地址
            //                 this.addEquipment.fastPrice = item.onePrice; //普通洗价格
            //                 this.addEquipment.exquisitePrice = item.twoPrice; //精洗价格
            //                 this.addEquipment.startTime = item.startTime; //营业起始时间
            //                 this.addEquipment.endTime = item.endTime; //营业结束时间
            //                 this.longitude = arr[0]; //经度
            //                 this.latitude = arr[1]; //纬度
            //             });

            //             this.theLocation(this.longitude, this.latitude);
            //         }
            //     });
        } else {
            this.$router.go(-1);
        }
    }
};
</script>

<style lang="scss" scoped>
</style>
